//
//  XFBFlowView.m
//  xfb
//
//  Created by XFB on 2022/4/14.
//  Copyright © 2022 XFB. All rights reserved.
//

#import "XFBFlowView.h"

#define Flow_ColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

@interface XFBFlowView ()

@property (nonatomic, strong) NSMutableArray *buttonLists;

@end

@implementation XFBFlowView

- (instancetype)init {
    self = [super init];
    if (self) {
        [self defaultConfig];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self defaultConfig];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self defaultConfig];
    }
    return self;
}

- (void)setLists:(NSMutableArray *)lists {
    _lists = lists;
    // 开始布局
    [self layout];
}

// 配置
- (void)defaultConfig {
    // 左边距
    self.leftMargin = 16;
    // 右边距
    self.rightMargin = 16;
    // 上下间距
    self.minimumLineSpacing = 12;
    // 左右间距
    self.minimumInteritemSpacing = 16;
    // 内边距
    self.padding = 10;
    // item高度
    self.itemHeight = 32;
    // item文本颜色
    self.itemTextColor = Flow_ColorFromRGB(0x333333);
    // item背景颜色
    self.itemBackgroudColor = Flow_ColorFromRGB(0xF7F7F7);
    // 字体大小
    self.itemTextFont = [UIFont systemFontOfSize:13];
    // 圆角
    self.itemRadius = 0;
}

// MARK: - 布局
- (void)layout {
    if (!self.lists) return;
    // 移除旧的数据
    for (UIButton *button in self.buttonLists) {
        [button removeFromSuperview];
    }
    [self.buttonLists removeAllObjects];
    
    // 左侧间距
    CGFloat leftMargin = self.leftMargin;
    // 右侧间距
    CGFloat rightMargin = self.rightMargin;
    // 水平间距 左右间距
    CGFloat minimumInteritemSpacing = self.minimumInteritemSpacing;
    // 行间距 上下间距
    CGFloat minimumLineSpacing = self.minimumLineSpacing;
    
    NSInteger count = self.lists.count;
    for (NSInteger i = 0; i < count; i ++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = 3200 + i;
        NSDictionary *tagDict = self.lists[i];
        [button setTitle:tagDict[@"name"] forState:UIControlStateNormal];
        [button setTitleColor:self.itemTextColor forState:UIControlStateNormal];
        button.titleLabel.font = self.itemTextFont;
        button.backgroundColor = self.itemBackgroudColor;
        button.layer.cornerRadius = self.itemRadius;
        button.layer.masksToBounds = YES;
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.buttonLists addObject:button];
        [self addSubview:button];
    }
    
    CGFloat buttonX = leftMargin;
    CGFloat buttonY = 0;
    CGFloat buttonW = 0;
    CGFloat buttonH = self.itemHeight;
    // 开始布局
    for (NSInteger i = 0; i < self.buttonLists.count; i ++) {
        UIButton *button = self.buttonLists[i];
        NSString *title = button.titleLabel.text;
        
        CGSize size = CGSizeMake(MAXFLOAT, self.itemHeight);
        NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
        attrs[NSFontAttributeName] = self.itemTextFont;
        buttonW = [title boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size.width + 2 * self.padding;

        // 左边距 + 右边距 + 标签宽度 + 标签间距 > self.width
        if (buttonX + buttonW + minimumInteritemSpacing + rightMargin > self.frame.size.width) {
            buttonX = leftMargin; // 换行
            buttonY = buttonY + buttonH + minimumLineSpacing;
        }
        
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        buttonX += buttonW + minimumInteritemSpacing; // 宽度 + 间隙
    }
    
    // 是否有更好的方法？
    UIButton *lastButton = self.buttonLists.lastObject;
   
    // self.height
    CGRect frame = self.frame;
    frame.size.height = CGRectGetMaxY(lastButton.frame);
    self.frame = frame;
    
    CGRect rect = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);

    if (self.frameBlock) {
        self.frameBlock(rect);
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(calculateFrame:)]) {
        [self.delegate calculateFrame:rect];
    }
}

// 点击tag
- (void)buttonClick:(UIButton *)sender {
    NSMutableArray *selectButtons = @[].mutableCopy;
    for (UIButton *button in self.buttonLists) {
        if (button.tag == sender.tag) {
            button.selected = !button.selected;
        }
        if (button.selected == YES) {
            [selectButtons addObject:button];
            button.layer.borderWidth = 0.5;
            button.layer.borderColor = Flow_ColorFromRGB(0x3DC9A9).CGColor;
            button.backgroundColor = Flow_ColorFromRGB(0xEDFCF6);
            [button setTitleColor:Flow_ColorFromRGB(0x1ABC9C) forState:UIControlStateNormal];
        } else {
            button.layer.borderWidth = 0.5;
            button.layer.borderColor = Flow_ColorFromRGB(0xF7F7F7).CGColor;
            button.backgroundColor = Flow_ColorFromRGB(0xF7F7F7);
            [button setTitleColor:Flow_ColorFromRGB(0x333333) forState:UIControlStateNormal];
        }
    }

    if (self.buttonBlock) {
        self.buttonBlock(selectButtons);
    }
}

// 计算布局
- (CGRect)calculateFlowViewFrame {
    if (!self.buttonLists) return CGRectZero;
    
    UIButton *lastButton = self.buttonLists.lastObject;
    
    // self.height
    CGRect frame = self.frame;
    frame.size.height = CGRectGetMaxY(lastButton.frame);
    self.frame = frame;
        
    CGRect rect = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    return rect;
}

- (NSMutableArray *)buttonLists {
    if (!_buttonLists) {
        _buttonLists = @[].mutableCopy;
    }
    return _buttonLists;
}

@end

